var express = require('express');
var router = express.Router();


const DB = require("../utils/db")
const { api_url } = require("../utils/config")



// 搜索数据
router.get("/searchlist", async (req, res, next) => {

    // 每一个都不是必传的------------------------------
    let { size = 6, page = 1,searchtext } = req.query

   if(!searchtext){
    next("请传递搜索内容")
    return
   }

    // 计算 下开始下标
    let index = (page - 1) * size
    // 查询当前页的数据
    let sql = `select   id,
                        cid,
                        title,
                        price,
                        CONCAT("${api_url}","/uploads/","course/",image_src)  as image_src, 
                        area_name,
                        subject_name
                from e_course 
                where status!=4 

                and  

               (title like "%${ searchtext }%" 
                or  area_name  like  "%${ searchtext }%"
                or  grade_name  like  "%${ searchtext }%"
                or  subject_name  like  "%${ searchtext }%"
                or  category_name  like  "%${ searchtext }%") 
        
                limit ${index},${size}`
    //不确定用户搜索的内容是什么，不确定应该把用户的内容跟数据库的哪一列数据去做比较，所以把有可能的情况都去判断一下------------------------


    let [err, result] = await DB(sql)

    if (err) {
        next("搜索请求失败")
        return
    }


    // 总页码：总条数/size
    let sql1 = `select id,
            cid,
            title,
            price,
            CONCAT("${api_url}","/uploads/","course/",image_src)  as image_src, 
            area_name,
            subject_name
        from e_course 
        where status!=4             
        and 
        (title like "%${ searchtext }%" 
        or  area_name  like  "%${ searchtext }%"
        or  grade_name  like  "%${ searchtext }%"
        or  subject_name  like  "%${ searchtext }%"
        or  category_name  like  "%${ searchtext }%")
        `

    let [err1, result1] = await DB(sql1)

    
    if (err1) {
        next("搜索失败")
        return
    }

    //总条数
    let sizes = result1.length;
    //总页码
    let pages = Math.ceil(sizes / size)


    res.send({
        status: 200,
        msg: searchtext+"搜索成功",
        result: {
            data: result,
            page: Number(page),
            pages,
            sizes
        }

    });
})




module.exports = router;